<template>
  <div class="dashboard-container">
    <el-card shadow="never" class="mt-2">
      <el-row class="h-80px">
        <el-col :span="18" :xs="24">
          <div class="flex-x-start">
            <el-avatar class="rounded-full" :src="userStore.userInfo.avatar" :size="80" />
            <div class="ml-5">
              <p style="margin: 0">{{ greetings }}</p>
              <div class="flex items-center">
                <p class="text-sm text-gray">
                  {{ sentence.quote }} - 《{{ sentence.source }}》{{ sentence.author }}
                </p>
                <!-- 复制 -->
                <el-icon class="cursor-pointer" style="margin-left: 10px" @click="handleCopy">
                  <CopyDocument />
                </el-icon>
                <el-icon class="cursor-pointer" style="margin-left: 10px" @click="handleRefresh">
                  <Refresh />
                </el-icon>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 系统管理员 数据统计 -->
    <el-row v-if="userStore.userInfo.roles.includes('ROOT')" :gutter="10" class="mt-5">
      <!-- 访客数(UV) -->
      <el-col :span="12">
        <el-skeleton :loading="visitStatsLoading" :rows="5" animated>
          <template #template>
            <el-card>
              <template #header>
                <div>
                  <el-skeleton-item variant="h3" style="width: 40%" />
                  <el-skeleton-item variant="rect" style="float: right; width: 1em; height: 1em" />
                </div>
              </template>

              <div class="flex-x-between">
                <el-skeleton-item variant="text" style="width: 30%" />
                <el-skeleton-item variant="circle" style="width: 2em; height: 2em" />
              </div>
              <div class="mt-5 flex-x-between">
                <el-skeleton-item variant="text" style="width: 50%" />
                <el-skeleton-item variant="text" style="width: 1em" />
              </div>
            </el-card>
          </template>
          <template v-if="!visitStatsLoading">
            <el-card shadow="never">
              <template #header>
                <div class="flex-x-between">
                  <span class="text-gray">访客数(UV)</span>
                  <el-tag type="success" size="small">日</el-tag>
                </div>
              </template>

              <div class="flex-x-between mt-2">
                <div class="flex-y-center">
                  <span class="text-lg">{{ visitStatsData.todayUvCount }}</span>
                  <span
                    :class="['text-xs', 'ml-2', getGrowthRateClass(visitStatsData.uvGrowthRate)]"
                  >
                    <el-icon>
                      <Top v-if="visitStatsData.uvGrowthRate > 0" />
                      <Bottom v-else-if="visitStatsData.uvGrowthRate < 0" />
                    </el-icon>
                    {{ formatGrowthRate(visitStatsData.uvGrowthRate) }}
                  </span>
                </div>
                <svg-icon icon-class="visitor" size="2em" />
              </div>

              <div class="flex-x-between mt-2 text-sm text-gray">
                <span>总访客数</span>
                <span>{{ visitStatsData.totalUvCount }}</span>
              </div>
            </el-card>
          </template>
        </el-skeleton>
      </el-col>

      <!-- 浏览量(PV) -->
      <el-col :span="12">
        <el-skeleton :loading="visitStatsLoading" :rows="5" animated>
          <template #template>
            <el-card>
              <template #header>
                <div>
                  <el-skeleton-item variant="h3" style="width: 40%" />
                  <el-skeleton-item variant="rect" style="float: right; width: 1em; height: 1em" />
                </div>
              </template>

              <div class="flex-x-between">
                <el-skeleton-item variant="text" style="width: 30%" />
                <el-skeleton-item variant="circle" style="width: 2em; height: 2em" />
              </div>
              <div class="mt-5 flex-x-between">
                <el-skeleton-item variant="text" style="width: 50%" />
                <el-skeleton-item variant="text" style="width: 1em" />
              </div>
            </el-card>
          </template>
          <template v-if="!visitStatsLoading">
            <el-card shadow="never">
              <template #header>
                <div class="flex-x-between">
                  <span class="text-gray">浏览量(PV)</span>
                  <el-tag type="primary" size="small">日</el-tag>
                </div>
              </template>

              <div class="flex-x-between mt-2">
                <div class="flex-y-center">
                  <span class="text-lg">{{ visitStatsData.todayPvCount }}</span>
                  <span
                    :class="['text-xs', 'ml-2', getGrowthRateClass(visitStatsData.pvGrowthRate)]"
                  >
                    <el-icon>
                      <Top v-if="visitStatsData.pvGrowthRate > 0" />
                      <Bottom v-else-if="visitStatsData.pvGrowthRate < 0" />
                    </el-icon>
                    {{ formatGrowthRate(visitStatsData.pvGrowthRate) }}
                  </span>
                </div>
                <svg-icon icon-class="browser" size="2em" />
              </div>

              <div class="flex-x-between mt-2 text-sm text-gray">
                <span>总浏览量</span>
                <span>{{ visitStatsData.totalPvCount }}</span>
              </div>
            </el-card>
          </template>
        </el-skeleton>
      </el-col>
    </el-row>

    <!-- 咨询师数据统计 -->
    <el-row v-if="userStore.userInfo.roles.includes('COUNSELOR')" :gutter="10" class="mt-5">
      <!-- 课程数量 -->
      <el-col :span="12">
        <el-card shadow="never">
          <div class="flex-x-between">
            <div class="stat-info">
              <p class="label">课程数量</p>
              <p class="value">{{ counselorStats?.courseCount }}</p>
            </div>
            <svg-icon icon-class="course" size="3em" />
          </div>
        </el-card>
      </el-col>

      <!-- 总咨询人数 -->
      <el-col :span="12">
        <el-card shadow="never">
          <div class="flex-x-between">
            <div class="stat-info">
              <p class="label">今日咨询人数</p>
              <p class="value">{{ counselorStats?.counselCount }}</p>
              <p class="trend" :class="{ up: counselorStats?.counselGrowth || 0 > 0 }">
                <el-icon>
                  <Top v-if="counselorStats?.counselGrowthRate > 0" />
                  <Bottom v-else style="color: red" />
                </el-icon>
                <span :style="counselorStats?.counselGrowthRate < 0 && 'color:red;'">
                  {{ formatGrowthRate(counselorStats?.counselGrowthRate || 0) }}
                </span>
              </p>
            </div>
            <svg-icon icon-class="user" size="3em" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 咨询师图表统计 -->
    <el-row v-if="userStore.userInfo.roles.includes('COUNSELOR')" :gutter="10" class="mt-5">
      <!-- 课程获赞统计 -->
      <el-col :span="12">
        <el-card shadow="never">
          <template #header>
            <div class="flex-x-between">
              <span>课程获赞统计</span>
              <el-tag type="success">总获赞: {{ courseLikeInfo?.likeTotal }}</el-tag>
            </div>
          </template>
          <div class="h-[400px]">
            <CourseLikes width="100%" height="100%" :data="courseLikeData" />
          </div>
        </el-card>
      </el-col>

      <!-- 课程评价统计 -->
      <el-col :span="12">
        <el-card shadow="never">
          <template #header>
            <div class="flex-x-between">
              <span>课程评价</span>
              <el-tag type="success">总计</el-tag>
            </div>
          </template>
          <div class="course-review-stats">
            <div class="stat-item">
              <div class="label">评论数量</div>
              <div class="value">{{ counselorStats?.courseReviewCount }}</div>
            </div>
            <el-divider />
            <div class="stat-item">
              <div class="label">好评率</div>
              <div class="value">{{ counselorStats?.courseGoodRate * 100 }}%</div>
            </div>
            <el-divider />
            <div class="stat-item">
              <div class="label">平均评分</div>
              <div class="value">
                <span style="font-size: 18px">{{ counselorStats?.courseAverageRating }}</span>
                /5
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 咨询趋势图 -->
    <el-row v-if="userStore.userInfo.roles.includes('COUNSELOR')" :gutter="10" class="mt-5">
      <el-col :span="24">
        <el-card shadow="never">
          <template #header>
            <div class="flex-x-between">
              <span>咨询趋势</span>
              <el-radio-group v-model="consultTrendTimeRange" size="small">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="h-[400px]">
            <ConsultTrend :time-range="consultTrendTimeRange" width="100%" height="100%" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 管理员数据统计 -->
    <template v-if="userStore.userInfo.roles.includes('ADMIN')">
      <!-- 咨询师审核统计 -->
      <el-row :gutter="10" class="mt-5">
        <el-col :span="12">
          <el-card shadow="never" class="audit-card">
            <template #header>
              <div class="flex-x-between">
                <span>咨询师审核</span>
                <el-button
                  v-if="adminStats?.pendingCounselorCount"
                  type="primary"
                  link
                  @click="handleGoToAudit('/counselor-manage/counselor/audit')"
                >
                  去处理
                </el-button>
              </div>
            </template>
            <div class="audit-stats">
              <div class="pending-box">
                <div class="number">{{ adminStats?.pendingCounselorCount || 0 }}</div>
                <div class="label">待审核</div>
              </div>
              <el-divider direction="vertical" />
              <div class="approved-box">
                <div class="number">{{ adminStats?.approvedCounselorCount || 0 }}</div>
                <div class="label">已审核</div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card shadow="never" class="audit-card">
            <template #header>
              <div class="flex-x-between">
                <span>课程审核</span>
                <el-button
                  v-if="adminStats?.pendingCourseCount"
                  type="primary"
                  link
                  @click="handleGoToAudit('/course-manage/course/audit')"
                >
                  去处理
                </el-button>
              </div>
            </template>
            <div class="audit-stats">
              <div class="pending-box">
                <div class="number">{{ adminStats?.pendingCourseCount || 0 }}</div>
                <div class="label">待审核</div>
              </div>
              <el-divider direction="vertical" />
              <div class="approved-box">
                <div class="number">{{ adminStats?.approvedCourseCount || 0 }}</div>
                <div class="label">已审核</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 评论和评价审核统计 -->
      <el-row :gutter="10" class="mt-5">
        <el-col :span="12">
          <el-card shadow="never" class="audit-card">
            <template #header>
              <div class="flex-x-between">
                <span>课程评论审核</span>
                <el-button
                  v-if="adminStats?.pendingCommentCount"
                  type="primary"
                  link
                  @click="handleGoToAudit('/courseReviewAudit')"
                >
                  去处理
                </el-button>
              </div>
            </template>
            <div class="audit-stats">
              <div class="pending-box">
                <div class="number">{{ adminStats?.pendingCommentCount || 0 }}</div>
                <div class="label">待审核</div>
              </div>
              <el-divider direction="vertical" />
              <div class="approved-box">
                <div class="number">{{ adminStats?.approvedCommentCount || 0 }}</div>
                <div class="label">已审核</div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card shadow="never" class="audit-card">
            <template #header>
              <div class="flex-x-between">
                <span>咨询师评价审核</span>
                <el-button
                  v-if="adminStats?.pendingReviewCount"
                  type="primary"
                  link
                  @click="handleGoToAudit('/consultantReviewAudit')"
                >
                  去处理
                </el-button>
              </div>
            </template>
            <div class="audit-stats">
              <div class="pending-box">
                <div class="number">{{ adminStats?.pendingReviewCount || 0 }}</div>
                <div class="label">待审核</div>
              </div>
              <el-divider direction="vertical" />
              <div class="approved-box">
                <div class="number">{{ adminStats?.approvedReviewCount || 0 }}</div>
                <div class="label">已审核</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="10" class="mt-5">
        <!-- 访问趋势统计图 -->
        <el-col v-if="userStore.userInfo.roles.includes('ROOT')" :xs="24" :span="16">
          <VisitTrend id="VisitTrend" width="100%" height="400px" />
        </el-col>
        <!-- 通知公告 -->
        <el-col :xs="24" :span="userStore.userInfo.roles.includes('ROOT') ? 8 : 24">
          <el-card>
            <template #header>
              <div class="flex-x-between">
                <div class="flex-y-center">通知公告</div>
                <el-link type="primary">
                  <span class="text-xs" @click="handleViewMoreNotice">查看更多</span>
                  <el-icon class="text-xs"><ArrowRight /></el-icon>
                </el-link>
              </div>
            </template>

            <el-scrollbar height="400px">
              <div v-for="(item, index) in notices" :key="index" class="flex-y-center py-4">
                <DictLabel v-model="item.type" code="notice_type" size="small" />
                <el-text truncated class="!mx-2 flex-1 !text-xs !text-gray">
                  {{ item.title }}
                </el-text>
                <el-link @click="handleOpenNoticeDetail(item.id)">
                  <el-icon class="text-sm"><View /></el-icon>
                </el-link>
              </div>
            </el-scrollbar>
          </el-card>
        </el-col>
      </el-row>
    </template>

    <NoticeDetail ref="noticeDetailRef" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});

import VisitTrend from "./components/visit-trend.vue";
import ConsultTrend from "./components/consult-trend.vue";
import CourseLikes from "./components/course-likes.vue";
import { useRouter } from "vue-router";

import LogAPI, { VisitStatsVO } from "@/api/system/log";
import NoticeAPI, { NoticePageVO } from "@/api/system/notice";
import { useUserStore } from "@/store/modules/user";
import { formatGrowthRate } from "@/utils";
import randomSentence, { SentenceType } from "@/utils/random-sentence";
import { copy } from "@/utils/copy";
import { getAdminDashboardInfo, getCourseLikeList, getDashboardInfo } from "@/api/dashbord";
import type { AdminStats, CourseLikeInfo, DashboardInfo } from "@/api/dashbord/type";

const router = useRouter();
const noticeDetailRef = ref();

const notices = ref<NoticePageVO[]>([]);

const userStore = useUserStore();
const date: Date = new Date();
const greetings = computed(() => {
  const hours = date.getHours();
  if (hours >= 6 && hours < 8) {
    return "晨起披衣出草堂，轩窗已自喜微凉🌅！";
  } else if (hours >= 8 && hours < 12) {
    return "上午好，" + userStore.userInfo.nickname + "！";
  } else if (hours >= 12 && hours < 18) {
    return "下午好，" + userStore.userInfo.nickname + "！";
  } else if (hours >= 18 && hours < 24) {
    return "晚上好，" + userStore.userInfo.nickname + "！";
  } else {
    return "偷偷向银河要了一把碎星，只等你闭上眼睛撒入你的梦中，晚安🌛！";
  }
});

const visitStatsLoading = ref(true);
const visitStatsData = ref<VisitStatsVO>({
  todayUvCount: 0,
  uvGrowthRate: 0,
  totalUvCount: 0,
  todayPvCount: 0,
  pvGrowthRate: 0,
  totalPvCount: 0,
});

// 咨询师统计数据
const counselorStats = ref<DashboardInfo>({
  courseCount: 0,
  counselCount: 0,
  todayCounselCount: 0,
  counselGrowth: 0,
  counselGrowthRate: 0,
  courseReviewCount: 0,
  courseReviewGoodCount: 0,
  courseGoodRate: 0,
  courseAverageRating: 0,
});

// 咨询趋势时间范围
const consultTrendTimeRange = ref<"week">("week");

// 管理员统计数据
const adminStats = ref<AdminStats>({
  pendingCounselorCount: 0,
  approvedCounselorCount: 0,
  pendingCourseCount: 0,
  approvedCourseCount: 0,
  pendingCommentCount: 0,
  approvedCommentCount: 0,
  pendingReviewCount: 0,
  approvedReviewCount: 0,
});

// 加载访问统计数据
const loadVisitStatsData = async () => {
  LogAPI.getVisitStats()
    .then((data) => {
      visitStatsData.value = data;
    })
    .finally(() => {
      visitStatsLoading.value = false;
    });
};

// 根据增长率获取样式
const getGrowthRateClass = (growthRate?: number): string => {
  if (!growthRate) {
    return "color-[--el-color-info]";
  }

  if (growthRate > 0) {
    return "color-[--el-color-danger]";
  } else if (growthRate < 0) {
    return "color-[--el-color-success]";
  } else {
    return "color-[--el-color-info]";
  }
};

const loadMyNotice = () => {
  NoticeAPI.getMyNoticePage({ pageNum: 1, pageSize: 10 }).then((data) => {
    notices.value = data.list;
  });
};

// 查看更多
function handleViewMoreNotice() {
  router.push({ path: "/myNotice" });
}

// 打开通知公告
function handleOpenNoticeDetail(id: string) {
  noticeDetailRef.value.openNotice(id);
}
const courseLikeData = ref();
const courseLikeInfo = ref<CourseLikeInfo>();
// 加载咨询师统计数据
const loadCounselorStats = async () => {
  if (userStore.userInfo.roles.includes("COUNSELOR")) {
    try {
      const data = await getDashboardInfo();
      counselorStats.value = data;
      const courseInfo = await getCourseLikeList();
      courseLikeInfo.value = courseInfo;
      courseLikeData.value = {
        courses: courseInfo.courseLikeList.map((item) => item.courseName),
        likes: courseInfo.courseLikeList.map((item) => item.likeNum),
      };
      console.log(courseLikeData, "courseLikeData");
    } catch (error) {
      console.error(error);
    }
  }
};

// 跳转到对应的审核页面
const handleGoToAudit = (path: string) => {
  router.push(path);
};

// 加载管理员统计数据
const loadAdminStats = async () => {
  if (userStore.userInfo.roles.includes("ADMIN")) {
    try {
      const data = await getAdminDashboardInfo();
      // 将API返回的数据映射到adminStats
      adminStats.value = {
        pendingCounselorCount: data.pendingCounselorCount || 0,
        approvedCounselorCount: data.approvedCounselorCount || 0,
        pendingCourseCount: data.pendingCourseCount || 0,
        approvedCourseCount: data.approvedCourseCount || 0,
        pendingCommentCount: data.pendingCommentCount || 0,
        approvedCommentCount: data.approvedCommentCount || 0,
        pendingReviewCount: data.pendingReviewCount || 0,
        approvedReviewCount: data.approvedReviewCount || 0,
      };
    } catch (error) {
      console.error(error);
    }
  }
};

onMounted(() => {
  if (userStore.userInfo.roles.includes("ROOT")) {
    loadVisitStatsData();
  }
  if (userStore.userInfo.roles.includes("ADMIN")) {
    loadAdminStats();
  }
  loadCounselorStats();
  loadMyNotice();
  handleRefresh();
});
const sentence = ref<SentenceType>({ quote: "", author: "", source: "" });
const handleRefresh = () => {
  sentence.value = randomSentence();
};
const handleCopy = () => {
  copy(sentence.value.quote + " - 《" + sentence.value.source + "》" + sentence.value.author);
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  position: relative;
  padding: 24px;

  .github-corner {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    border: 0;
  }

  .stat-info {
    .label {
      color: var(--el-text-color-secondary);
      font-size: 14px;
      margin: 0;
    }
    .value {
      font-size: 24px;
      font-weight: bold;
      margin: 8px 0;
    }
    .trend {
      font-size: 12px;
      color: var(--el-color-danger);
      display: flex;
      align-items: center;
      gap: 4px;
      &.up {
        color: var(--el-color-success);
      }
    }
  }

  .course-review-stats {
    padding: 20px 0;
    .stat-item {
      text-align: center;
      padding: 10px 0;
      .label {
        color: var(--el-text-color-secondary);
        font-size: 14px;
        margin-bottom: 8px;
      }
      .value {
        font-size: 24px;
        font-weight: bold;
        color: var(--el-color-primary);
      }
    }
  }

  .audit-card {
    .audit-stats {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20px 0;
      text-align: center;

      .pending-box,
      .approved-box {
        flex: 1;
        .number {
          font-size: 36px;
          font-weight: bold;
          line-height: 1;
          margin-bottom: 10px;
        }
        .label {
          color: var(--el-text-color-secondary);
          font-size: 14px;
        }
      }

      .pending-box .number {
        color: var(--el-color-danger);
      }

      .approved-box .number {
        color: var(--el-color-success);
      }
    }
  }
}
</style>
